#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright @ 2014 OPS, Qunar Inc. (qunar.com)
#
# Author: tingfang.bao <tingfang.bao@qunar.com>
# DateTime: 15-3-10 下午4:44
import json
from database import db_session
from flask import Flask
from models import User

app = Flask(__name__)


@app.teardown_appcontext
def shutdown_session(exception=None):
    db_session.remove()


@app.route("/")
def index():
    # 下面这两种方法都可以，都是原生的SQLAlchemy支持的
    # users = db_session.query(User).all()
    users = User.query.all()
    ret = []
    for user in users:
        ret.append({
            "name": user.username,
            "id": user.id,
            "email": user.email
        })
    return json.dumps(ret)


@app.route('/add')
def create():
    user = User("hanjing", "douzi406@163.com")
    db_session.add(user)
    db_session.commit()
    return 'added'


if __name__ == '__main__':
    app.run(debug=True)